package com.moss.cloud.remote.biz.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.moss.cloud.common.core.utils.BooleanHandel;
import com.moss.cloud.remote.api.model.from.IPAddrFrom;
import com.moss.cloud.remote.api.model.vo.IPAddrVO;
import com.moss.cloud.remote.biz.constant.RemoteErroryType;
import com.moss.cloud.remote.biz.service.IPService;
import com.moss.cloud.remote.biz.utils.BaiDuIpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class IPServiceImpl implements IPService {

    /**
     * 获取IP地址信息
     *
     * @param from
     * @return
     */
    public IPAddrVO getIpAddr(IPAddrFrom from) {
        IPAddrVO ipAddrVO = new IPAddrVO();
        JSONObject object = BaiDuIpUtil.getIpAddr(from.getIpAddress());
        BooleanHandel.trueThrow(!object.getInteger("status").equals(BaiDuIpUtil.STATUS)).throwMessage(RemoteErroryType.BAI_DU_IP_API_ERROR);
        //获取省份
        String province = ((JSONObject) ((JSONObject) object.get("content")).get("address_detail")).getString("province");
        //获取城市
        String city = ((JSONObject) ((JSONObject) object.get("content")).get("address_detail")).getString("city");
        //获取城市码
        String cityCode = ((JSONObject) ((JSONObject) object.get("content")).get("address_detail")).getString("city_code");
        //获取地址
        String address = ((JSONObject) object.get("content")).get("address").toString();
        //获取经度
        String longitude = ((JSONObject) ((JSONObject) object.get("content")).get("point")).getString("x");
        //获取纬度
        String latitude = ((JSONObject) ((JSONObject) object.get("content")).get("point")).getString("y");
        ipAddrVO.setIpAddress(from.getIpAddress());
        ipAddrVO.setAddress(address);
        ipAddrVO.setProvince(province);
        ipAddrVO.setCity(city);
        ipAddrVO.setCityCode(cityCode);
        ipAddrVO.setLongitude(longitude);
        ipAddrVO.setLatitude(latitude);
        return ipAddrVO;
    }

}

